package com.ourhours.message.rpc.service.impl;

import com.alibaba.fastjson.JSON;
import com.ourhours.global.response.ApiResponse;
import com.ourhours.global.response.ApiResponseBuilder;
import com.ourhours.message.constant.ConstantMQ;
import com.ourhours.message.api.SmsRpcService;
import com.ourhours.message.domain.SmsSend;
import com.ourhours.message.domain.Supplier;
import com.ourhours.message.domain.Template;
import com.ourhours.message.enums.ApiResponseCode;
import com.ourhours.message.enums.MessageTypeEnum;
import com.ourhours.message.exception.MessageException;
import com.ourhours.message.request.SmsCustomContentRequest;
import com.ourhours.message.request.SmsTemplateContentRequest;
import com.ourhours.message.request.SmsTypeContentRequest;
import com.ourhours.message.response.MmsBaseResponse;
import com.ourhours.message.response.MmsBaseResponseCode;
import com.ourhours.message.service.SmsSendService;
import com.ourhours.message.service.TemplateService;
import com.ourhours.message.service.wrapper.SmsWrapper;
import com.ourhours.message.service.wrapper.SupplierWrapper;
import com.ourhours.redismq.RedisMQMessageSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("smsRpcService")
public class SmsRpcServiceImpl implements SmsRpcService {


    private static final Logger LOGGER = LoggerFactory.getLogger(SmsRpcServiceImpl.class);

    @Autowired
    SmsSendService smsSendService;

    @Autowired
    JmsTemplate jmsTemplate;

    @Autowired
    RedisMQMessageSender messageSender;


    @Autowired
    TemplateService templateService;

    @Autowired
    SupplierWrapper supplierWrapper;

    @Autowired
    SmsWrapper smsWrapper;

    @Override
    public ApiResponse<Boolean> sendMessage(SmsCustomContentRequest smsCustomContentRequest) {

        String phone = smsCustomContentRequest.getPhone();
        Long vendorId = smsCustomContentRequest.getVendorId();
        String content = smsCustomContentRequest.getContent();

        //从缓存中获取运营商信息
        Supplier supplier = supplierWrapper.findSupplierWithCache(vendorId,MessageTypeEnum.SMS.getCode());
        if(supplier==null){
            LOGGER.error("获取营运商信息失败");
            return ApiResponseBuilder.buildSuccess(false);
        }
        //接受消息，保存数据库
        SmsSend smsSend = new SmsSend();
        smsSend.setPhone(phone);
        smsSend.setVendorId(vendorId);
        smsSend.setContent(content);
        smsSend.setSupplierId(supplier.getId());
        smsSend.setCreateTime(new Date());
        smsSend.setUpdateTime(new Date());
        smsSend.setCreateUser(phone);
        smsSend.setUpdateUser(phone);
        try{
            smsSend.setStatus(0);
            Boolean status = smsSendService.insert(smsSend);
            Long redisResult = messageSender.put(new com.ourhours.redismq.Message(ConstantMQ.smsSendMQ, JSON.toJSONString(smsSend)));
            if(redisResult==null){
                //报警
                smsWrapper.smsAlarmInfo(vendorId);
                //直接发
                boolean result = smsSendService.sendMessage(smsSend);
                if(result){
                    smsSend.setStatus(1);
                    smsSendService.updateById(smsSend);
                    LOGGER.info("发送短信成功：参数:{},{},{}, 结果:{}",phone,vendorId,content,result);
                    return ApiResponseBuilder.buildSuccess(true);
                }else{
                    smsSend.setStatus(2);
                    smsSend.setFailureCode("-1");
                    smsSend.setFailureReason("直发失败");
                    smsSendService.updateById(smsSend);
                    LOGGER.info("发送短信失败：参数:{},{},{}, 结果:{}",phone,vendorId,content,result);
                    return ApiResponseBuilder.buildError(MmsBaseResponseCode.SEND_PHONE_CODE_ERROR.code,MmsBaseResponseCode.SEND_PHONE_CODE_ERROR.msg);
                }
            }
            LOGGER.info("发送MQ成功：参数:{},{},{}, 结果:{}",phone,vendorId,content,status);
            return ApiResponseBuilder.buildSuccess(true);
        }catch (MessageException me){
            LOGGER.info("发送短信失败：参数:{},{},{}, 结果:{}",phone,vendorId,content,me);
            return ApiResponseBuilder.buildSuccess(false);
        }catch (Exception e1){
            LOGGER.info("发送短信失败：参数:{},{},{}, 结果:{}",phone,vendorId,content,e1);
            return ApiResponseBuilder.buildSuccess(false);
        }
    }

    /**
     * 发送有模版内容的消息
     */
    @Override
    public ApiResponse<Boolean> sendMessageWithTemplate(SmsTemplateContentRequest smsTemplateContentRequest){

        String phone = smsTemplateContentRequest.getPhone();
        Long vendorId = smsTemplateContentRequest.getVendorId();
        Long templateId = smsTemplateContentRequest.getTemplateId();
        Map<Integer,String> templateData = smsTemplateContentRequest.getTemplateData();

        //从缓存中获取运营商信息
        Supplier supplier = supplierWrapper.findSupplierWithCache(vendorId,MessageTypeEnum.SMS.getCode());
        if(supplier==null){
            LOGGER.error(",参数:{},结果:{}",vendorId,supplier);
            throw new MessageException("根据vendorId查询推送供应商表数据为空！");
        }

        SmsSend smsSend = new SmsSend();
        smsSend.setPhone(phone);
        smsSend.setVendorId(vendorId);
        smsSend.setSupplierId(supplier.getId());
        smsSend.setSmsType(9999);//自定义模板
        smsSend.setCreateTime(new Date());
        smsSend.setUpdateTime(new Date());
        smsSend.setCreateUser(phone);
        smsSend.setUpdateUser(phone);

        //获取到模板内容，替换
        Template templateEntity = templateService.getTemplateById(templateId);
        if(templateEntity==null){
            LOGGER.info("获取模板失败：参数:{}, 结果:{}",smsTemplateContentRequest,templateEntity);
            return ApiResponseBuilder.buildError(ApiResponseCode.ERROR.getCode(),ApiResponseCode.ERROR.getMessage());
        }
        String content = templateEntity.getContent();
        try {
            for (Integer key : templateData.keySet()) {
                content = content.replace("${"+key+"}", templateData.get(key));
            }
            smsSend.setContent(content);
            smsSend.setStatus(0);
            Boolean  status = smsSendService.insert(smsSend);
            Long redisResult = messageSender.put(new com.ourhours.redismq.Message(ConstantMQ.smsSendMQ, JSON.toJSONString(smsSend)));
            if(redisResult==null){
                //报警
                smsWrapper.smsAlarmInfo(vendorId);
                //直接发
                boolean result = smsSendService.sendMessage(smsSend);
                if(result){
                    smsSend.setStatus(1);
                    smsSendService.updateById(smsSend);
                    LOGGER.info("发送短信成功：参数:{},{},{}, 结果:{}",phone,vendorId,content,result);
                    return ApiResponseBuilder.buildSuccess(true);
                }else{
                    smsSend.setStatus(2);
                    smsSend.setFailureCode("-1");
                    smsSend.setFailureReason("直发失败");
                    smsSendService.updateById(smsSend);
                    LOGGER.error("发送短信失败：参数:{},{},{}, 结果:{}",phone,vendorId,content,result);
                    return ApiResponseBuilder.buildError(MmsBaseResponseCode.SEND_PHONE_CODE_ERROR.code,MmsBaseResponseCode.SEND_PHONE_CODE_ERROR.msg);
                }
            }
            LOGGER.info("发送MQ成功：参数:{},{},{}, 结果:{}",phone,vendorId,templateId,status);
            return ApiResponseBuilder.buildSuccess(true);
        }catch (MessageException me){
            LOGGER.error("发送短信失败：参数:{},{},{}, 结果:{}",phone,vendorId,content,me);
            return ApiResponseBuilder.buildError(MmsBaseResponseCode.SEND_PHONE_CODE_ERROR.code,MmsBaseResponseCode.SEND_PHONE_CODE_ERROR.msg);
        }catch (Exception e){
            LOGGER.error("发送短信失败：参数:{},{},{}, 结果:{}",phone,vendorId,content,e);
            return ApiResponseBuilder.buildError(MmsBaseResponseCode.SEND_PHONE_CODE_ERROR.code,MmsBaseResponseCode.SEND_PHONE_CODE_ERROR.msg);
        }
    }

    public static void main(String[] args) {
        Map<Integer,String> templateData = new HashMap<Integer, String>();
        templateData.put(1,"aaaaa");
        templateData.put(2,"bbbbbbb");
        templateData.put(3,"ccccc");
        templateData.put(4,"ddddd");
        String content="您的订单${1}已准备好，请及时提货。如有疑问请联系门店${2}。。。";
        String template="验证码：${1}，5分钟内有效，请勿泄露或转发他人。";
        String content2 = template.replace("${1}", "132132");
        for (Integer key : templateData.keySet()) {
            System.out.println(templateData.get(key));
            System.out.println(key);
            content = content.replace("${"+key+"}", templateData.get(key));
        }
        System.out.println(content);
        System.out.println(content2);
    }
    @Override
    public ApiResponse<Boolean> sendMessageWithTypeTemplate(SmsTypeContentRequest smsTypeContentRequest) {
        String phone = smsTypeContentRequest.getPhone();
        Long vendorId = smsTypeContentRequest.getVendorId();
        int smsType = smsTypeContentRequest.getSmsType().getCode();
        Map<Integer,String> templateData = smsTypeContentRequest.getTemplateData();

        //从缓存中获取运营商信息
        Supplier supplier = supplierWrapper.findSupplierWithCache(vendorId,MessageTypeEnum.SMS.getCode());
        if(supplier==null){
            LOGGER.error("获取供应商信息失败,参数:{},结果:{}",vendorId,supplier);
            throw new MessageException("根据vendorId查询推送供应商表数据为空！");
        }
        SmsSend smsSend = new SmsSend();
        smsSend.setPhone(phone);
        smsSend.setVendorId(vendorId);
        smsSend.setSupplierId(supplier.getId());
        smsSend.setCreateTime(new Date());
        smsSend.setUpdateTime(new Date());
        smsSend.setCreateUser(phone);
        smsSend.setUpdateUser(phone);

        //获取到模板内容，替换
        Template templateEntity = templateService.getTemplateByType(smsType,vendorId);
        if(templateEntity==null){
            LOGGER.error("获取模板失败：参数:{}, 结果:{}",smsTypeContentRequest,templateEntity);
            return ApiResponseBuilder.buildSuccess(false);
        }
        String content = templateEntity.getContent();
        try {
            for (Integer key : templateData.keySet()) {
                content = content.replace("${"+key+"}", templateData.get(key));
            }
            smsSend.setContent(content);
            smsSend.setStatus(0);
            Boolean  status = smsSendService.insert(smsSend);
            Long redisResult = messageSender.put(new com.ourhours.redismq.Message(ConstantMQ.smsSendMQ, JSON.toJSONString(smsSend)));
            if(redisResult==null){
                //报警
                smsWrapper.smsAlarmInfo(vendorId);
                //直接发
                boolean result = smsSendService.sendMessage(smsSend);
                if(result){
                    smsSend.setStatus(1);
                    smsSendService.updateById(smsSend);
                    LOGGER.info("发送自定义短信成功：参数:{},结果:{}",smsTypeContentRequest,result);
                    return ApiResponseBuilder.buildSuccess(true);
                }else{
                    smsSend.setStatus(2);
                    smsSend.setFailureCode("-1");
                    smsSend.setFailureReason("直发失败");
                    smsSendService.updateById(smsSend);
                    LOGGER.error("发送自定义短信失败：参数:{},结果:{}",smsTypeContentRequest,result);
                    return ApiResponseBuilder.buildError(MmsBaseResponseCode.SEND_PHONE_CODE_ERROR.code,MmsBaseResponseCode.SEND_PHONE_CODE_ERROR.msg);
                }
            }
            LOGGER.info("发送自定义模板MQ成功：参数:{},{},{}, 结果:{}",smsTypeContentRequest,status);
            return ApiResponseBuilder.buildSuccess(true);

        }catch (MessageException me){
            LOGGER.error("发送自定义短信失败：参数:{},结果:{}",smsTypeContentRequest,me);
            return ApiResponseBuilder.buildError(MmsBaseResponseCode.SEND_PHONE_CODE_ERROR.code,MmsBaseResponseCode.SEND_PHONE_CODE_ERROR.msg);
        }catch (Exception e){
            LOGGER.error("发送自定义短信失败：参数:{},结果:{}",smsTypeContentRequest,e);
            return ApiResponseBuilder.buildError(MmsBaseResponseCode.SEND_PHONE_CODE_ERROR.code,MmsBaseResponseCode.SEND_PHONE_CODE_ERROR.msg);
        }

    }

}
